//账套&法人&公司 三合一 页面
// 对不起 把这个页面 写复杂了……  因为后端其实就一个接口  这个接口承担了 关键词搜索 和 账套/法人/公司的搜索 还有翻页 联动等等
// 如果看不懂代码 欢迎咨询 欧阳柯 虽然本人也 不一定 能短时间 理清楚了…… 头疼
import React, { Component } from "react";
import "styles/enterprise-manage/set-of-books-company/set-of-books-company.scss";
import { Input, Button, Dropdown, Icon, Menu, Popover, Select, Tabs } from "antd";
import { deepCopy, messages } from "share/common";
import { connect } from "react-redux";
import { Buttons } from "containers/enterprise-manage/set-of-books-company/set-of-books-company.modal";
import SlideFrame from "components/slide-frame";
import NewSetOfBooks from "containers/finance-setting/set-of-books/new-set-of-books";
import NewLegalPerson from "containers/enterprise-manage/legal-person/new-legal-person";
import NewCompanyMaintain from "containers/enterprise-manage/company-maintain/new-company-maintain";
import importExportService from "containers/enterprise-manage/set-of-books-company/set-of-books-compnay-importHandeler.service";
import SetOfBooksCompanyService from "containers/enterprise-manage/set-of-books-company/set-of-books-company.service";

import SetOfBooksComp from "containers/enterprise-manage/set-of-books-company/components/set-of-books-comp";
import LegalPersonComp from "containers/enterprise-manage/set-of-books-company/components/legal-person-comp";
import CompanyComp from "containers/enterprise-manage/set-of-books-company/components/company-comp";
import LegalPersonDisplayComp from "containers/enterprise-manage/set-of-books-company/components/legal-person-display-comp";

import LegalPerson from "containers/enterprise-manage/legal-person/legal-person";
import CompanyDefineIndex from "containers/enterprise-manage/company-maintain/company-define-index";
import SVGIcon from "components/SVGIcon";
import TipEn from "images/enterprise-manage/tip_en.jpg";
import TipZh from "images/enterprise-manage/tip_zh.jpg";

import debounce from "lodash.debounce";

const InputGroup = Input.Group;
const { Option } = Select;
const TabPane = Tabs.TabPane;

function mapStateToProps(state) {
  return {
    language: state.main.language,
    currentPageRoute: state.main.currentPageRoute,
    isOldCompany: state.login.isOldCompany,
  };
}

@connect(mapStateToProps)
class SetOfBooksCompany extends Component {
  constructor(props) {
    super(props);
    const { currentPageRoute, isOldCompany } = props;
    const showKeyArray = currentPageRoute.subFunctions
      .filter((item) => item.operationType !== "H")
      .map((item) => item.functionCode);
    this.state = {
      tabValue: showKeyArray[0],
      typeValue: isOldCompany ? "LEGAL_ENTITY" : "COMPANY",
      loadingData: {
        setOfBooksLoading: false,
        legalPersonLoading: false,
        companyLoading: false,
      },
      allData: {
        setOfBooksDTOPage: { content: [] },
        legalEntityPage: { content: [] },
        companyPage: { content: [] },
      },
      allPage: {
        COMPANY: 0,
        SET_OF_BOOK: 0,
        LEGAL_ENTITY: 0,
      },
      keyword: "",
      allActiveLegalPerson: false,
      allActiveCompany: false,
      noDataFromBooks: false,
    };
    this.typePlaceholderMap = {
      COMPANY: messages("basic-5.key955") /*公司名称/编码*/,
      LEGAL_ENTITY: messages("basic-5.key206") /*法人实体名称*/,
      ALL: messages("basic-5.key956") /*公司名称/编码/法人实体名称*/,
    };
    this.currentParams = {};
    this.currentParams_setOfBooksDTOPage = null;
    this.currentParams_legalEntityPage = null;
    this.currentParams_companyPage = null;
    this.currentParams_last_companyId = null;
    this.currentParams_last_legalEntityId = null;
    this.currentParams_last_setOfBooksId = null;
    this.currentSelect = null;
    //this.currentParams  当前的搜索params 用于 翻页
    //this.currentParams_xxx  法人/账套/公司 各自的 当前翻页后的 params 一般都是 page >= 1了
    //this.currentParams_last_xxx   法人/账套/公司 各自的 上一状态的 params （为什么是要上一状态，因为如果取最新的状态 翻页是无数据的，因为联动时，点击联动的）
    this.searchData = debounce(this.searchData, 300);
    this.getAllData = debounce(this.getAllData, 300);
    this.keyMap = {
      companyId: "companyPage",
      legalEntityId: "legalEntityPage",
      setOfBooksId: "setOfBooksDTOPage",
    };
  }

  componentWillMount() {
    this.getAllData();
  }

  componentDidMount() {}

  componentWillUnmount() {}

  onSelect = (key, item, refreshItSelf = false) => {
    const { isOldCompany } = this.props;
    this.currentSelect = { key, item };
    switch (key) {
      case "setOfBooksId":
        this.getAllData({
          loadingArray: ["legalPersonLoading", "companyLoading"],
          dataArray: ["legalEntityPage", "companyPage"],
          linkMode: !!item,
          otherParams: {
            setOfBooksId: item && item[key],
          },
          linkData: {
            key,
            item,
            setOfBooksId: item && item.setOfBooksId,
          },
          refreshItSelf: refreshItSelf
            ? {
                key: "setOfBooksDTOPage",
                target: item && item.setOfBooksId,
              }
            : false,
        });
        break;
      case "legalEntityId":
        if (isOldCompany) {
          this.handleActive({
            key,
            item,
            setOfBooksId: item && item.setOfBooksId,
          });
        } else {
          this.getAllData({
            loadingArray: item ? ["companyLoading"] : ["legalPersonLoading", "companyLoading"],
            dataArray: item ? ["companyPage"] : ["legalEntityPage", "companyPage"],
            linkMode: !!item,
            otherParams: {
              setOfBooksId: item && item.setOfBooksId,
              legalEntityId: item && item.id,
            },
            linkData: {
              key,
              item,
              setOfBooksId: item && item.setOfBooksId,
            },
            refreshItSelf: refreshItSelf
              ? {
                  key: "legalEntityPage",
                  target: item && item.id,
                }
              : false,
          });
        }
        break;
      case "companyId":
        this.getAllData({
          loadingArray: item ? ["legalPersonLoading"] : ["legalPersonLoading", "companyLoading"],
          dataArray: item ? ["legalEntityPage"] : ["legalEntityPage", "companyPage"],
          linkMode: !!item,
          otherParams: {
            setOfBooksId: item && item.setOfBooksId,
            legalEntityId: item && item.legalEntityId,
            companyId: item && item.id,
          },
          linkData: {
            key,
            item,
            setOfBooksId: item && item.setOfBooksId,
          },
          refreshItSelf: refreshItSelf
            ? {
                key: "companyPage",
                target: item && item.id,
              }
            : false,
        });
        break;
    }
  };

  handleActive = ({ setOfBooksId, item, key } = {}) => {
    if (item) {
      if (["companyId", "legalEntityId"].includes(key)) {
        this.setOfBooksCompRef && this.setOfBooksCompRef.setSelectedKeys([`${setOfBooksId}`], true);
        if (key === "companyId") {
          this.setState({ allActiveLegalPerson: true, allActiveCompany: false, noDataFromBooks: false });
          this.legalPersonCompRef && this.legalPersonCompRef.setActiveId();
        } else if (key === "legalEntityId") {
          this.setState({ allActiveCompany: true, allActiveLegalPerson: false, noDataFromBooks: false });
          this.companyCompRef && this.companyCompRef.setActiveId();
        }
      } else {
        this.setState({ allActiveCompany: true, allActiveLegalPerson: true, noDataFromBooks: true });
        this.companyCompRef && this.companyCompRef.setActiveId();
        this.legalPersonCompRef && this.legalPersonCompRef.setActiveId();
      }
    } else {
      this.setOfBooksCompRef && this.setOfBooksCompRef.setSelectedKeys([]);
      this.setState({ allActiveLegalPerson: false, allActiveCompany: false, noDataFromBooks: false });
      this.companyCompRef && this.companyCompRef.setActiveId();
      this.legalPersonCompRef && this.legalPersonCompRef.setActiveId();
    }
  };

  getAllData = ({
    loadingArray = ["setOfBooksLoading", "legalPersonLoading", "companyLoading"],
    dataArray = ["setOfBooksDTOPage", "legalEntityPage", "companyPage"],
    linkMode = false,
    otherParams = {},
    linkData = {},
    getNextPage = false,
    key = undefined,
    refreshItSelf = false,
  } = {}) => {
    // console.log("搜索", loadingArray, dataArray, linkMode, otherParams, linkData, getNextPage);
    const { typeValue, keyword, allData, loadingData } = this.state;
    Object.keys(loadingData).forEach((key) => {
      if (loadingArray.includes(key)) {
        loadingData[key] = true;
      }
    });
    let params = {
      page: 0,
      size: 10,
      ...otherParams,
    };
    if (getNextPage) {
      params = deepCopy(
        this[`currentParams_last_${key}`] || this[`currentParams_${dataArray[0]}`] || this.currentParams
      );
      params.page += 1;
    } else if (keyword && !linkMode) {
      params.keyword = keyword;
      params.searchModel = typeValue;
      this.handleActive({});
    }
    this.setState({ loadingData });
    SetOfBooksCompanyService.getAllData(params).then((res) => {
      if (res.status === 200) {
        if (!getNextPage) {
          if (linkMode) {
            if (!this[`currentParams_last_${linkData.key}`]) {
              this.currentParams_last_companyId = null;
              this.currentParams_last_legalEntityId = null;
              this.currentParams_last_setOfBooksId = null;
              this[`currentParams_last_${linkData.key}`] =
                this[`currentParams_${this.keyMap[linkData.key]}`] || this.currentParams;
            }
          } else if (!linkData.item) {
            this.currentParams_last_companyId = null;
            this.currentParams_last_legalEntityId = null;
            this.currentParams_last_setOfBooksId = null;
          }
          this.currentParams = params;
          this.currentParams_setOfBooksDTOPage = null;
          this.currentParams_legalEntityPage = null;
          this.currentParams_companyPage = null;
        } else {
          this.currentParams_last_companyId = null;
          this.currentParams_last_legalEntityId = null;
          this.currentParams_last_setOfBooksId = null;
          this[`currentParams_${dataArray[0]}`] = params;
        }
        if (linkMode) {
          this.handleActive(linkData);
        } else if (!getNextPage) {
          this.handleActive({});
        }
        Object.keys(allData).forEach((key) => {
          if (dataArray.includes(key)) {
            if (res.data[key]) {
              if (getNextPage) {
                allData[key].content = allData[key].content.concat(res.data[key].content);
              } else {
                allData[key] = res.data[key];
              }
            }
          }
          if (refreshItSelf) {
            if (refreshItSelf.key === key) {
              allData[key].content.find((item, index) => {
                if (item.id === refreshItSelf.target) {
                  allData[key].content[index] = res.data[key].content[0];
                  return true;
                }
              });
            }
          }
        });
        this.setState(
          {
            allData,
            loadingData: {
              setOfBooksLoading: false,
              legalPersonLoading: false,
              companyLoading: false,
            },
          },
          () => {
            if (getNextPage) {
              this.handleNextPageLoading(dataArray);
            }
          }
        );
      }
    });
  };

  handleNextPageLoading = (dataArray) => {
    const key = dataArray[0];
    switch (key) {
      case "setOfBooksDTOPage":
        this.setOfBooksCompRef && this.setOfBooksCompRef.setMoreLoading(false);
        break;
      case "legalEntityPage":
        this.legalPersonCompRef && this.legalPersonCompRef.setMoreLoading(false);
        break;
      case "companyPage":
        this.companyCompRef && this.companyCompRef.setMoreLoading(false);
        break;
    }
  };

  onGetMore = (key) => {
    switch (key) {
      case "COMPANY":
        this.getAllData({ loadingArray: [], dataArray: ["companyPage"], getNextPage: true, key: "companyId" });
        break;
      case "LEGAL_ENTITY":
        this.getAllData({ loadingArray: [], dataArray: ["legalEntityPage"], getNextPage: true, key: "legalEntityId" });
        break;
      // case "SET_OF_BOOK":
      //   this.getAllData({
      //     loadingArray: [],
      //     dataArray: ["setOfBooksDTOPage"],
      //     getNextPage: true,
      //     key: "setOfBooksId",
      //   });
      //   break;
    }
  };

  searchData = () => {
    const { typeValue } = this.state;
    switch (typeValue) {
      case "COMPANY":
        this.getAllData({ loadingArray: ["companyLoading"], dataArray: ["companyPage"] });
        break;
      case "LEGAL_ENTITY":
        this.getAllData({ loadingArray: ["legalPersonLoading"], dataArray: ["legalEntityPage"] });
        break;
      case "ALL":
        this.getAllData({
          loadingArray: ["legalPersonLoading", "companyLoading"],
          dataArray: ["legalEntityPage", "companyPage"],
        });
        break;
    }
  };

  handleChangeSelect = (typeValue) => {
    this.setState({ typeValue }, () => {
      if (this.state.keyword) this.searchData();
    });
  };

  keywordChange = (e) => {
    const keyword = e.target.value;
    this.setState({ keyword }, () => {
      this.searchData();
    });
  };

  handleAddNew = (item) => {
    switch (item.key) {
      case "add-set-of-book":
        this.openSlideFrame({
          title: messages("basic-5.key145") /*新建账套*/,
          data: { setOfBooksId: null },
          content: NewSetOfBooks,
          afterClose: () => {
            this.handleAfterClose("", true);
          },
        });
        break;
      case "add-legal-entity":
        this.openSlideFrame({
          title: messages("basic-5.key231") /*新增法人实体*/,
          data: { legalPersonOID: null },
          content: NewLegalPerson,
          afterClose: () => {
            this.handleAfterClose("", true);
          },
        });
        break;
      case "add-company":
        this.openSlideFrame({
          title: messages("basic-5.key186") /*新建公司*/,
          data: { id: null },
          content: NewCompanyMaintain,
          afterClose: () => {
            this.handleAfterClose("", true);
          },
        });
        break;
    }
  };

  handleEdit = (key, data) => {
    switch (key) {
      case "edit-set-of-book":
        this.openSlideFrame({
          title: messages("basic-5.key146") /*编辑账套*/,
          data,
          content: NewSetOfBooks,
        });
        break;
      case "edit-legal-entity":
        this.openSlideFrame({
          title: data.titleName,
          data,
          content: LegalPersonDisplayComp,
          hasFooter: false,
          // afterClose: () => {
          //   this.getAllData({ loadingArray: ["legalPersonLoading"], dataArray: ["legalEntityPage"] });
          // },
        });
        break;
      case "edit-company":
        this.openSlideFrame({
          title: messages("basic-5.key175") /*编辑公司*/,
          data,
          content: NewCompanyMaintain,
        });
        break;
    }
  };

  handleView = (key, data) => {
    switch (key) {
      case "view-company":
        this.openSlideFrame({
          title: data.titleName,
          data: { onlyView: true, ...data },
          content: NewCompanyMaintain,
          afterClose: (key) => {
            if (key) {
              this.handleAfterClose();
            }
          },
        });
        break;
    }
  };

  //打开侧拉 编辑 外部报表
  openSlideFrame = ({ title, data, content, hasFooter = true, afterClose = this.handleAfterClose }) => {
    SlideFrame.open(
      {
        title: title,
        width: "800px",
        afterClose,
        params: data,
        content: content,
        hasFooter,
      },
      this
    );
  };

  handleAfterClose = (key, updateAll = false) => {
    // switch (key) {
    //   case "setOfBooks":
    //     this.getAllData({ loadingArray: ["setOfBooksLoading"], dataArray: ["setOfBooksDTOPage"] });
    //     this.handleActive({});
    //     break;
    //   case "legalEntity":
    //     this.getAllData({ loadingArray: ["legalPersonLoading"], dataArray: ["legalEntityPage"] });
    //     this.handleActive({});
    //     break;
    //   case "company":
    //     this.getAllData({ loadingArray: ["companyLoading"], dataArray: ["companyPage"] });
    //     this.handleActive({});
    //     break;
    // }
    if (this.currentSelect && this.currentSelect.item && !updateAll) {
      this.onSelect(this.currentSelect.key, this.currentSelect.item, true);
    } else {
      this.getAllData({});
      this.handleActive({});
    }
  };

  renderMenuName = (btn) => {
    const importMap = ["import-legal-person", "import-company"];
    const exportMap = ["export-legal-entity", "export-company-info", "export-company-bank-info"];
    if (importMap.includes(btn.key)) {
      return importExportService.importHandler(btn, this);
    } else if (exportMap.includes(btn.key)) {
      return importExportService.exportHandler(btn);
    }
    return btn.name;
  };

  onGoToCompanyGroup = () => {
    this.setState({ tabValue: "company-list-tab" }, () => {
      this.companyDefineIndexRef &&
        this.companyDefineIndexRef.handleRadioChange({ target: { value: "company-group" } });
    });
  };

  handleTabsChange = (e) => {
    this.setState({ tabValue: e });
    switch (e) {
      case "set-of-books-tab":
        this.getAllData();
        this.legalPersonCompRef && this.legalPersonCompRef.getScope();
        break;
      case "legal-entity-list-tab":
        this.legalPerson && this.legalPerson.getScope();
        this.legalPerson && this.legalPerson.afterClose();
        break;
      case "company-list-tab":
        this.companyDefineIndexRef && this.companyDefineIndexRef.refresh();
    }
  };

  render() {
    const {
      loadingData,
      allData,
      typeValue,
      keyword,
      allActiveLegalPerson,
      allActiveCompany,
      tabValue,
      noDataFromBooks,
    } = this.state;
    const { language, currentPageRoute, isOldCompany } = this.props;
    const showKeyArray = currentPageRoute.subFunctions
      .filter((item) => item.operationType !== "H")
      .map((item) => item.functionCode);
    const hideKeys = ["add-company", "import-company", "export-company-info", "export-company-bank-info"]; //老租户 需要屏蔽掉 与 公司相关的
    return (
      <div className="set-of-books-company full-height-page-88 full-page-margin">
        <Tabs activeKey={tabValue} onChange={this.handleTabsChange}>
          {showKeyArray.includes("set-of-books-tab") && (
            <TabPane tab={messages("basic-5.key957") /*账套/法人/公司*/} key={"set-of-books-tab"}>
              <div className="top-box">
                <div className="button-search-box">
                  {Buttons.map((type) => {
                    return (
                      <Dropdown
                        trigger={["hover"]}
                        overlay={
                          <Menu onClick={this.handleAddNew}>
                            {type.children.map((btn) => {
                              if (isOldCompany && hideKeys.includes(btn.key)) {
                                return <span />;
                              }
                              return (
                                <Menu.Item style={{ textAlign: "left" }} key={btn.key}>
                                  {this.renderMenuName(btn)}
                                </Menu.Item>
                              );
                            })}
                          </Menu>
                        }
                        placement="bottomLeft"
                      >
                        <Button type={type.type === "add" ? "primary" : "default"}>
                          {type.btnName}
                          <Icon type="down" />
                        </Button>
                      </Dropdown>
                    );
                  })}
                </div>
                <div className="search-input-box">
                  <InputGroup compact style={{ width: "384px" }}>
                    <Select value={typeValue} style={{ width: "27%" }} onChange={this.handleChangeSelect}>
                      {!isOldCompany && <Option value="COMPANY">{messages("basic-5.key1") /*公司*/}</Option>}
                      <Option value="LEGAL_ENTITY">{messages("basic-5.key182") /*法人*/}</Option>
                      {!isOldCompany && <Option value="ALL">{messages("common.all") /*全部*/}</Option>}
                    </Select>
                    <Input
                      allowClear
                      value={keyword}
                      prefix={<Icon type="search" />}
                      style={{ width: "73%" }}
                      onChange={this.keywordChange}
                      placeholder={this.typePlaceholderMap[typeValue]}
                    />
                  </InputGroup>
                  <Popover
                    placement="bottomRight"
                    content={
                      <div className={"img-tip-box"}>
                        <img src={language.code === "zh_cn" ? TipZh : TipEn} className="img" />
                      </div>
                    }
                    getPopupContainer={() => document.querySelector(".set-of-books-company")}
                  >
                    <div className="light-bulb">
                      <SVGIcon className={"light-bulb-icon"} type={"light-bulb-tip"} />
                    </div>
                  </Popover>
                </div>
              </div>
              <div className="set-of-books-company-content">
                <SetOfBooksComp
                  onRef={(ref) => (this.setOfBooksCompRef = ref)}
                  onSelect={this.onSelect}
                  // onGetMore={this.onGetMore}
                  data={allData.setOfBooksDTOPage}
                  onEdit={this.handleEdit}
                  loading={loadingData.setOfBooksLoading}
                />
                <LegalPersonComp
                  onlyLeft={isOldCompany}
                  keyword={["LEGAL_ENTITY", "ALL"].includes(typeValue) ? keyword : ""}
                  onRef={(ref) => (this.legalPersonCompRef = ref)}
                  allActive={allActiveLegalPerson}
                  onSelect={this.onSelect}
                  onGetMore={this.onGetMore}
                  data={allData.legalEntityPage}
                  onEdit={this.handleEdit}
                  loading={loadingData.legalPersonLoading}
                />
                <CompanyComp
                  hide={isOldCompany}
                  showCompanyGroup={showKeyArray.includes("company-list-tab")}
                  onGoToCompanyGroup={this.onGoToCompanyGroup}
                  keyword={["COMPANY", "ALL"].includes(typeValue) ? keyword : ""}
                  onRef={(ref) => (this.companyCompRef = ref)}
                  allActive={allActiveCompany}
                  noDataFromBooks={noDataFromBooks}
                  onSelect={this.onSelect}
                  onGetMore={this.onGetMore}
                  data={allData.companyPage}
                  onView={this.handleView}
                  // onEdit={this.handleEdit}
                  loading={loadingData.companyLoading}
                />
              </div>
            </TabPane>
          )}
          {showKeyArray.includes("legal-entity-list-tab") && (
            <TabPane tab={messages("basic-5.key958") /*法人实体列表*/} key={"legal-entity-list-tab"}>
              <LegalPerson onRef={(ref) => (this.legalPerson = ref)} />
            </TabPane>
          )}
          {showKeyArray.includes("company-list-tab") && (
            <TabPane tab={messages("basic-5.key959") /*公司列表*/} key={"company-list-tab"}>
              <CompanyDefineIndex onRef={(ref) => (this.companyDefineIndexRef = ref)} />
            </TabPane>
          )}
        </Tabs>
      </div>
    );
  }
}

SetOfBooksCompany.propTypes = {};

export default SetOfBooksCompany;
